/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import Axios from "axios";
import { MusicList } from "../Models/MusicList.schema";
import { createMusicListDTO, updateMusicListDTO } from "../DTO/MusicList.dto";
import { isExistsforId, isExistsforTitle } from "../hook";
import { createMusicDTO } from "../DTO/Music.dto"
export class MusicListController {
  constructor(private readonly musicListModel: typeof MusicList) { }

  /**
   * 创建歌单
   * @param dto 数据传输对象
   * @returns 返回创建对象
   */
  async createItem(dto: createMusicListDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await this.musicListModel.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }

  /**
   * 以ID为查找依据删除歌单
   * @param id 要删除元素的唯一ID
   * @returns
   */
  async removeById(id: string) {
    try {
      if (!await isExistsforId(id, this.musicListModel)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "删除成功",
          data: await this.musicListModel.deleteOne({ _id: id }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新歌单
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateMusicListDTO) {
    try {
      if (!await isExistsforId(id, this.musicListModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.musicListModel.updateOne({ _id: id }, dto),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按歌单名称查找歌单
   * @param title 要查找的歌单名称
   * @returns 查询对象
   */
  async findByTitle(title: string) {
    try {
      const reg = new RegExp(`${title}`, 'g')
      if (!await isExistsforTitle(title, this.musicListModel)) {
        //网易云查询
        const data = await Axios.get(`http://162.14.104.16:3005/search?keywords=${title}}&type=1000&limit=50`, { withCredentials: true })
        const res = await data.data as {
          code: number;
          result: {
            playlistCount: number;
            playlists: {
              id: string;//歌单id
              name: string; //名称
              coverImgUrl: string; // 封面
              creator: {
                nickname: string;
              }; //创作者
              description: string; //介绍
            }[];
          }
        };
        console.log(res.result.playlists)
        // 只录入前10条数据
        if (res.result.playlistCount > 0) {
          for (let i = 0; i < res.result.playlists.length; i++) {
            if (i === 80) { break; }
            let tempData = {
              //歌单唯一标识
              _id: res.result.playlists[i].id,
              // 歌单名称
              name: res.result.playlists[i].name,
              //作者
              auther: res.result.playlists[i].creator.nickname,
              //封面
              cover: res.result.playlists[i].coverImgUrl,
              //播放地址
              link: res.result.playlists[i].id,
              //介绍
              introduce: res.result.playlists[i].description,
            } as createMusicListDTO

            // 添加到数据库
            await this.createItem(tempData);
          }

          return {
            code: 200,
            message: '查询成功',
            data: await this.musicListModel.find({ name: reg }),
          }
        }
        return {
          code: 400,
          message: '不存在查询的Title',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.musicListModel.find({ name: reg }),
        };
      }
    } catch (error) {
      return await error;
    }
  }
  /**
   * 按ID查找歌单
   * @param id 要查找的歌单名称
   * @returns 查询对象
   */
  async findById(id: string) {
    try {
      if (!await isExistsforId(id, this.musicListModel)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.musicListModel.find({ _id: id }),
        };
      }
    } catch (error) {
      return false;
    }
  }
  //查询全部数据
  async findAll() {
    try {
      if (await this.musicListModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.musicListModel.find(),
        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }
  //随机获取指定条数的数据
  async findBySize(size: number) {
    try {
      return {
        code: 200,
        message: "查询成功",
        data: await this.musicListModel.aggregate([{ $sample: { size: size } }])
      }

    } catch (error) {
      return error;
    }
  }
  //first
  //获取歌单详情
  async getMusicListInfo(id: string) {
    try {
      const data = await Axios.get(`http://162.14.104.16:3005/playlist/detail?id=${id}`)
      const res = data.data as {
        code: string,
        relatedVideos: string,
        playlist: {
          name: string,
          id: string,
          coverImgUrl: string,
          createTime: string,
          trackCount: string,//歌曲数目
          description: string,
          tags: [string],//标签
          tracks: [{
            id: string;
            name: string;
            ar: any;
            al: any;
            picUrl: string;
          }],//歌曲列表
          trackIds: [{
            id: string
          }]
        }
      };
      return {
        code: 200,
        message: "获取成功",
        data: res.playlist,
      }
    } catch (error) {
      return error;
    }
  }
  //获取歌单分类
  async getClass() {
    try {
      const data = await Axios.get("http://162.14.104.16:3005/playlist/catlist")
      const res = data.data as {
        code: string,
        all: object,
        sub: {
          name: string,
          category: number
        }[],
        categories: object
      };
      return {
        code: 200,
        message: "获取成功",
        data: {
          all: res.all,
          sub: res.sub,
          categories: res.categories,
        }
      }
    } catch (error) {
      return error;
    }

  }
  //获取歌单列表
  async getList(limit: number, page: number, type: string) {
    try {
      const data = await Axios.get(`http://162.14.104.16:3005/top/playlist?limit=${limit}&ofset=${page}&cat=${type}`)
      // const res = data.data as {
      //   playlists: [object],
      //   total: number,
      // };
      return {
        code: 200,
        message: "获取成功",
        data: data.data
      }
    } catch (error) {
      return error;
    }

  }
}
